//
//  LCPNetWorking.m
//  网络请求类封装
//
//  Created by lanou3g on 15/10/24.
//  Copyright © 2015年 李成鹏.com. All rights reserved.
//

#import "LCPNetWorking.h"

@interface LCPNetWorking ()

@property (nonatomic, strong) NSMutableURLRequest *request;

@end

@implementation LCPNetWorking

static LCPNetWorking *lcpNet;
+(instancetype)defaultLcpWoring{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lcpNet = [LCPNetWorking new];
        lcpNet.request = [NSMutableURLRequest new];
    });
    return lcpNet;
}

// 获取网络数据接口
-(void)getNetWorkingData:(NSString *)baseURL Method:(NSString *)method Parameter:(NSDictionary *)par CallBack:(CallBack)callBack{
    [self getNetData:baseURL Parameter:par Method:method CallBack:^(id object,id error) {
        NSData *data = (NSData *)object;
        if (data == nil) {
            callBack(nil,error);
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                id parseData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
                if (parseData) {
                    callBack(parseData,nil);
                } else{
                    if (error == nil) {
                       NSError *e = [NSError errorWithDomain:@"未能请求到数据" code:-777777 userInfo:nil];
                        callBack(nil,e);
                    } else{
                        callBack(nil,error);
                    }
                }
            });
        }
    }];
}

// 获取网络数据私有方法
- (void)getNetData:(NSString *)baseURL Parameter:(NSDictionary *)par Method:(NSString *)method CallBack:(CallBack)callBack{
    // 创建请求对象
    [self.request setURL:[NSURL URLWithString:baseURL]];
    if ([method isEqualToString:@"post"]) {
        // 设置请求方式
        [_request setHTTPMethod:method];
        // 设置请求参数
        NSData *tempData = [self httpBodyFromParamDictionary:par];
        [_request setHTTPBody:tempData];
    }
    if ([method isEqualToString:@"get"] && par) {
        [self setParamForHttpRequestWithUrl:baseURL Param:par];
    }
    // 创建session会话
    NSURLSession *session = [NSURLSession sharedSession];
    // 创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:_request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            callBack(data,error);
    }];
    [task resume];
}

// 请求参数设置  post
- (NSData *)httpBodyFromParamDictionary:(NSDictionary *)params
{
    NSMutableString * data = [NSMutableString string];
    for (NSString * key in params.allKeys) {
        [data appendFormat:@"%@=%@&",key,params[key]];
    }
    return [[data substringToIndex:data.length-1] dataUsingEncoding:NSUTF8StringEncoding];
}

// 请求参数设置 get
- (void)setParamForHttpRequestWithUrl:(NSString *)Url Param:(NSDictionary *)par{
    NSMutableString *urlParamStr = [NSMutableString string];
    for (NSString *key in par.allKeys) {
        [urlParamStr appendFormat:@"%@=%@&",key,par[key]];
    }
    [self.request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",Url,[urlParamStr substringToIndex:urlParamStr.length - 1]]]];
}

- (void)setHttpHeaderFieldValue:(id)value forKey:(NSString *)key{
    [self.request setValue:value forHTTPHeaderField:key];
}

@end
